"""
	Developerd by Andrea Stagi <stagi.andrea@gmail.com>
	TwittLine - the client twitter on your terminal
	Copyright (C) 2010 Andrea Stagi

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import tweepy
import tweepy.error
from modules.graphic import twittcolor
import twittutils
import twittconsts
import os
import pickle


class page:

	size=twittconsts.PAGEINC
	minmess=18
	block_upd=0
	statuses=None
	user=None
	title=""
	api=tweepy.API()
	query=""
	errmsg=""
	sccmsg=""
	page=20

	help=""
	helpls=""
	help_page=twittconsts.HELP_PAGES
	help_pagels=twittconsts.HELP_R_PAGES


	hid=0

	def attachApi(self,api):
		self.api=api

	def resetPosition(self):
		return None

	def show(self):
		i=0

		if(self.title!=""):
			twittcolor.colorprintln(self.title,0)

		print ""

    		if self.statuses:
			
        		for i in range(0, self.size):
				if(i<len(self.statuses)):	
	            			self.showMyStatus(i,self.statuses[i])
				else:
					break

		#twittcolor.colorprintln("%d twitts on page %d" % (self.size,len(self.statuses)),2)

		self.showHelp()

		if(self.errmsg!=""):
			twittcolor.colorprintln("ERROR: %s" % (self.errmsg),0)
			self.errmsg=""

		if(self.sccmsg!=""):
			twittcolor.colorprintln("%s" % (self.sccmsg),0)
			self.sccmsg=""


	def showMyStatus(self,status):
		return self;

	def showHelp(self):
		if(self.hid==1):
			print "Global: " + self.help_page
			print "Here:   " + self.help
		elif(self.hid==2):
			print "Global: " + self.help_pagels
			print "Here:   " + self.helpls

	def setHelp(self,id):
		self.hid=id

	def update(self,text):
		return self

	def directmess(self,screen_name,text):
		try:
			self.api.send_direct_message(screen_name=screen_name, text=text)
		except tweepy.error.TweepError as details:
			self.errmsg="" + details.reason
		else:
			self.sccmsg="Message sent! See your direct messages.."
	
	def delete(self,id):
		return self
	
	def load(self,query):
		return self

	def favorite(self,id_mess):
		return self

	def unfavorite(self,id_mess):
		return self

	def next(self):

		self.size=self.size+twittconsts.PAGEINC
		self.load(self.query)

	def prev(self):
		if(self.size-twittconsts.PAGEINC!=0):
			self.size=self.size-twittconsts.PAGEINC
			self.load(self.query)

	def reply(self,id_mess,text):
		return self

	def retweet(self,id_mess):
		return self

	def follow(self,id_usr):
		return self

	def unfollow(self,id_usr):
		return self

	def more(self):
		return self

	def less(self):
		return self

	def getFollowers(self):
		return self

	def getFollowing(self):
		return self

	def getFavorites(self):
		return self

class page_status(page):

	def showMyStatus(self,i,status):
		if(not status.favorited):
			twittcolor.colorprintln("[%d] %s - %s [%s] \n" % (i+1, status.user.screen_name, status.text,status.created_at),i%2)
		else:
			twittcolor.colorprint("[%d] %s - %s [%s] " % (i+1, status.user.screen_name, status.text,status.created_at),i%2)
			twittcolor.colorprintln("*\n",2)

	def update(self,text):
		try:
			self.api.update_status(text)
		except tweepy.error.TweepError as details:
			self.errmsg="update status failed!" + details.reason

	def delete(self,id_mess):
		try:
			self.api.destroy_status(self.statuses[id_mess-1].id)
		except tweepy.error.TweepError as details:
			self.errmsg="" + details.reason

	def reply(self,id_mess,text):
		if(id_mess<=self.size):
			self.update("@%s %s" % (self.statuses[id_mess-1].user.screen_name, text))
		else:
			self.errmsg="You're out of range!"

	def retweet(self,id_mess):
		if(id_mess<=self.size):
			try:		
				self.api.retweet(self.statuses[id_mess-1].id)
			except tweepy.error.TweepError as details:
				self.errmsg="" + details.reason
			else:
				self.sccmsg="Retweet done! See your retweets.."
		else:
			self.errmsg="You're out of range!"

	def favorite(self,id_mess):
		try:
			self.api.create_favorite(self.statuses[id_mess-1].id)
		except tweepy.error.TweepError as details:
			self.errmsg="" + details.reason

	def unfavorite(self,id_mess):
		try:
			self.api.destroy_favorite(self.statuses[id_mess-1].id)
		except tweepy.error.TweepError as details:
			self.errmsg="" + details.reason
		else:
			self.sccmsg="Unfavorite done! See your favorites.."

	def getFavorites(self):
		fvs=favorites()
		fvs.attachApi(self.api)
		fvs.load(query=self.user.id)
		return fvs

class direct_mess(page):

	wiam=1

	def showMyStatus(self,i,status):
		if(self.wiam==1):
			twittcolor.colorprintln("[%d] %s - %s [%s]\n" % (i+1, status.sender.screen_name, status.text,status.created_at),i%2)
		else:
			twittcolor.colorprintln("[%d] %s - %s [%s]\n" % (i+1, status.recipient.screen_name, status.text,status.created_at),i%2)


	def load(self,query=""):


		if(query==">>"):
			try:
				self.statuses=self.api.sent_direct_messages(page=self.page)
			except tweepy.error.TweepError as details:
				self.errmsg="Open sent direct messages failed!" + details.reason

			self.title="Sent direct messages"
			self.query=query
			self.wiam=0

		else:
			try:
				self.statuses=self.api.direct_messages(page=self.page)
			except tweepy.error.TweepError as details:
				self.errmsg="Open Inbox failed!" + details.reason

			self.title="My Inbox"
			self.query=query
			self.wiam=1

	def delete(self,id_mess):
		try:
			self.api.destroy_direct_message(self.statuses[id_mess-1].id)
		except tweepy.error.TweepError as details:
			self.errmsg="" + details.reason

	def reply(self,id_mess,text):

		user=None		

		if(id_mess<=self.size):

			if(self.wiam==1):	
				user=self.statuses[id_mess-1].sender
			else:
				user=self.statuses[id_mess-1].recipient

			try:
				self.api.send_direct_message(screen_name=user.screen_name, text=text)
			except tweepy.error.TweepError as details:
				self.errmsg="" + details.reason
		else:
			self.errmsg="You're out of range!"



class page_users(page):

	def showMyStatus(self,i,status):
		twittcolor.colorprintln("[%d] %s(%s) - You follow: %s Location: %s Verified: %s\n" % (i+1, status.name, status.screen_name, 			status.following,status.location, status.verified),i%2)



	def follow(self,id_usr):
		if(id_usr<=self.size):
			if(self.statuses[id_usr-1].following==False):
				try:
					self.api.create_friendship(self.statuses[id_usr-1].screen_name)
				except tweepy.error.TweepError as details:
					self.errmsg="You can't follow "	+ self.statuses[id_usr-1].screen_name + " " + details.reason
			
				self.load(query=self.query)
		else:
			self.errmsg="You're out of range!"

	def unfollow(self,id_usr):
		if(id_usr<=self.size):
			if(self.statuses[id_usr-1].following==False):
				try:
					self.api.destroy_friendship(self.statuses[id_usr-1].screen_name)
				except tweepy.error.TweepError as details:
					self.errmsg="You can't unfollow " + self.statuses[id_usr-1].screen_name + " " + details.reason
			
				self.load(query=self.query)
		else:
			self.errmsg="You're out of range!"

	def delete(self,id_mess):
		if(id_mess<=self.size):		
			if(self.statuses[id_mess-1].user.screen_name==(self.api.me()).screen_name):
				page_status.delete(self,id_mess)
		else:
			self.errmsg="You're out of range!"

class favorites(page_status):

	help= twittconsts.HELP_FAVS
	helpls= twittconsts.HELP_R_FAVS

	def load(self,query=""):

		#self.size=twittconsts.PAGEINC		

		try:
			self.statuses = self.api.favorites(id=query,count=self.size)
		except tweepy.error.TweepError as details:
			self.errmsg=details.reason

		self.title="Favorite tweets"

	def getFavorites(self):
		return self


class home(page_status):

	upd=0

	help= twittconsts.HELP_HOME
	helpls= twittconsts.HELP_R_HOME

	def load(self,query=""):

		self.user=self.api.me()

		#self.size=twittconsts.PAGEINC		

		try:
			saux = self.api.home_timeline(count=self.size)
		except tweepy.error.TweepError as details:
			self.errmsg=details.reason
		else:
			i=0
			self.upd=0

			if(self.statuses!=None and self.block_upd!=1):
				self.block_upd=0
				for s in saux:
					if((s.user.screen_name == self.statuses[0].user.screen_name) and (s.text == self.statuses[0].text)):
						break
					else:
						self.upd+=1
					i+=1

			self.statuses=saux

		self.title="My home (%d %s" % (self.upd , "new Twitts)")
		self.sccmsg="Home updated (%d %s" % (self.upd , "new Twitts)")


class retweets(page_status):

	help= twittconsts.HELP_RETW
	helpls= twittconsts.HELP_R_RETW


	def load(self,query=""):

		self.user=self.api.me()

		#self.size=twittconsts.PAGEINC		

		if(query==""):
			try:
				self.statuses = self.api.retweeted_to_me(count=self.size)
			except tweepy.error.TweepError as details:
				self.errmsg="Retweeted to me failed open.." + details.reason
			else:
				self.title="Retweeted to me"

		elif(query=="<<"):
			try:
				self.statuses = self.api.retweets_of_me(count=self.size)
			except tweepy.error.TweepError as details:
				self.errmsg="Retweeted of me failed open.." + details.reason
			else:
				self.title="Retweeted of me"

		elif(query==">>"):
			try:
				self.statuses = self.api.retweeted_by_me(count=self.size)
			except tweepy.error.TweepError as details:
				self.errmsg="Retweeted by me failed open.." + details.reason
			else:
				self.title="Retweeted by me"


class profile(page_status):

	wantMore=False

	help=twittconsts.HELP_PROFILE_ME
	helpls=twittconsts.HELP_R_PROFILE_ME

	def attachApi(self,api):
		self.user=api.me()
		page.attachApi(self,api)
	
	def showMyStatus(self,i,status):
		if(not status.favorited):
			twittcolor.colorprintln("[%d] %s [%s] \n" % (i+1, status.text,status.created_at),i%2)
		else:
			twittcolor.colorprint("[%d] %s [%s] " % (i+1, status.text,status.created_at),i%2)
			twittcolor.colorprintln("*\n",2)
			

	def show(self):
		
		if(self.wantMore==False):

			twittcolor.colorprintln("[+] %s(%s) - You follow: %s Location: %s" % (self.user.name, self.user.screen_name, 				self.user.following,self.user.location),1)
		
		else:

			twittcolor.colorprintln("[-] %s(%s) - You follow: %s Location: %s" % (self.user.name, self.user.screen_name, 				self.user.following,self.user.location),1)

			twittcolor.colorprintln("[-] Web: %s Bio: %s " % ( self.user.url, self.user.description),1)

			twittcolor.colorprintln("[-] Verified: %s Following: %d Followers: %d " % ( self.user.verified, self.user.followers_count, 				self.user.friends_count),1)

		print ""
		page.show(self)

	def more(self):
		self.wantMore=True

	def less(self):
		self.wantMore=False

	def load(self,query=""):
		
		self.query=query
		self.wantMore=False
		
		if(query=="<<"):		

			try:
				self.statuses = self.api.user_timeline(count=self.size)
			except tweepy.error.TweepError as details:
				self.errmsg=details.reason
			else:
				self.user=self.api.me()
				#self.size=twittconsts.PAGEINC
		
				self.help=twittconsts.HELP_PROFILE_ME
				self.helpls=twittconsts.HELP_R_PROFILE_ME

		elif(query==""):
			try:
				self.statuses = self.api.user_timeline(screen_name=self.user.screen_name,count=self.size)
			except tweepy.error.TweepError as details:
				self.errmsg="%s profile can't be viewed..%s" % (self.user.screen_name,details.reason)
				
		else:

			try:
				#self.user = tweepy.api.get_user(query) - this method has a bug..
				self.user=self.api.search_users(q=self.query)[0]
			except tweepy.error.TweepError as details:
				self.errmsg="%s profile can't be viewed..%s" % (query,details.reason) 
			else:
				self.statuses = self.api.user_timeline(screen_name=self.user.screen_name,count=self.size)

				self.help=twittconsts.HELP_PROFILE
				self.helpls=twittconsts.HELP_R_PROFILE

	def follow(self,id_usr=""):
		if(self.user.following==False):
			try:
				self.api.create_friendship(self.user.id)
			except tweepy.error.TweepError as details:
				self.errmsg="You can't follow %s..%s" % (self.user.screen_name,details.reason) 

	def unfollow(self,id_usr=""):
		if(self.user.following==False):
			try:
				self.api.destroy_friendship(self.user.id)
			except tweepy.error.TweepError as details:
				self.errmsg="You can't unfollow %s..%s" % (self.user.screen_name,details.reason) 

	def reply(self,id_mess,text):
		if((self.api.me()).screen_name!=self.user.screen_name):
			page_status.reply(self,id_mess,text)

	def retweet(self,id_mess):
		if((self.api.me()).screen_name!=self.user.screen_name):
			page_status.retweet(self,id_mess)

	def getFollowers(self):
		flw=followers()
		flw.attachApi(self.api)
		flw.load(query=self.user.screen_name)
		return flw

	def getFollowing(self):
		flw=following()
		flw.attachApi(self.api)
		flw.load(query=self.user.screen_name)
		return flw

class search(page_users):
		
	help=twittconsts.HELP_SEARCH
	helpls=twittconsts.HELP_R_SEARCH

	def load(self,query=""):
		if(query!=""):
			self.resetPosition()
			self.query=query
			self.statuses = self.api.search_users(q=self.query,page=self.size/20)
			self.title="Looking for " + query

class following(page_users):

	help=twittconsts.HELP_SEARCH
	helpls=twittconsts.HELP_R_SEARCH

	def load(self,query=""):
		self.resetPosition()
		if(query!=""):
			self.query=query
		
		try:		
			self.statuses = self.api.friends(screen_name=self.query,count=self.size)
		except tweepy.error.TweepError as details:
			self.errmsg="" + details.reason

		self.title="Following - " + self.query


class followers(page_users):

	help=twittconsts.HELP_SEARCH
	helpls=twittconsts.HELP_R_SEARCH

	def load(self,query=""):
		self.resetPosition()
		if(query!=""):
			self.query=query
		try:
			self.statuses = self.api.followers(screen_name=self.query,count=self.size)
		except tweepy.error.TweepError as details:
			self.errmsg="" + details.reason
		
		self.title="Followers - " + self.query


		


